package com.telnetnz.ticketdesk.action.acp.project;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.telnetnz.ticketdesk.action.base.BasicSessionPageAcpAction;
import com.telnetnz.ticketdesk.action.common.CommonUtils;
import com.telnetnz.ticketdesk.bean.Project;
import com.telnetnz.ticketdesk.bean.User;
import com.telnetnz.ticketdesk.service.OperationLogService;
import com.telnetnz.ticketdesk.service.ProjectService;
import com.telnetnz.ticketdesk.service.ProjectToUserService;
import com.telnetnz.ticketdesk.service.UserService;

public class AcpProjectEditAction extends BasicSessionPageAcpAction
{
	private static Logger logger = Logger.getLogger(AcpProjectEditAction.class);

	public String doAddMember()
	{
		RequestBean bean = new DefaultRequestBean();
		int projectId = bean.getInt("project_id");
		int userId = bean.getInt("user_id");
		int role = bean.getInt("role", 0, 0, ProjectToUserService.ROLES.length - 1);
		Project project = ProjectService.getProject(projectId);
		User user = UserService.getUser(userId);
		if (project != null && user != null)
		{
			ProjectToUserService.add(projectId, userId, role);
			OperationLogService.addLog(
					OperationLogService.OBJECT_TYPE_PROJECT,
					projectId,
					getSession().getSession_uuid(),
					getContext().getActionName(),
					OperationLogService.createSimpleDiff("user", new String[]{user.getName(), ProjectToUserService.ROLES[role]}));
		}
		return redirect(bean.getRedirect());
	}

	public String doDelete()
	{
		RequestBean bean = new DefaultRequestBean();
		int id = bean.getInt("id");
		Project project = ProjectService.getProject(id);
		if (project == null)
		{
			return message_box(
					langRes.get("global.error"), 
					langRes.get("project.project-not-exist", new String[]{bean.getRedirect()}),
					bean.getRedirect(),
					3
				);
		}

		int target_id = bean.getInt("target_id");
		if (bean.isSubmitted())
		{
			if (bean.get("confirm").length() > 0)
			{
				Project target = ProjectService.getProject(target_id);
				ProjectService.delete(project, target);

				OperationLogService.addLog(
						OperationLogService.OBJECT_TYPE_PROJECT,
						project.getId(), 
						getSession().getSession_uuid(), 
						getContext().getActionName(),
						null);

				return message_box(
						langRes.get("global.operation-success"), 
						langRes.get("project.project-delete-success-redirect", new String[]{bean.getRedirect()}),
						bean.getRedirect(),
						2
					);
			}
			else
			{
				return this.redirect(bean.getRedirect());
			}
		}

		List<Integer> excludedIds = new ArrayList<Integer>();
		excludedIds.add(id);
		String project_option = CommonUtils.buildProjectDropdown(
				ProjectService.getByPageAndCondition(
						0, 
						100, 
						ProjectService.ORDERBY_NAME, 
						1,
						excludedIds), 
				0, 
				true);
		String extra_html = 
				"<select id=\"target_id\" name=\"target_id\">" + project_option + "</select>"
				+ ((bean.getError_msg().get("target_id") == null)? "" : bean.getError_msg().get("target_id"));

		Map<String, String> form = new HashMap<String, String>();
		form.put("id", ""+ id);
		form.put("redirect", bean.getRedirect());
		return confirm_box(
				langRes.get("global.confirm"), 
				langRes.get("project.confirm-delete-message"),
				baseLink(), 
				extra_html, 
				form);
	}

	public String doDeleteMember()
	{
		RequestBean bean = new DefaultRequestBean();
		int projectId = bean.getInt("project_id");
		int userId = bean.getInt("user_id");
		Project project = ProjectService.getProject(projectId);
		User user = UserService.getUser(userId);
		if (project != null && user != null)
		{
			ProjectToUserService.delete(projectId, userId);
			OperationLogService.addLog(
					OperationLogService.OBJECT_TYPE_PROJECT,
					projectId,
					getSession().getSession_uuid(),
					getContext().getActionName(),
					OperationLogService.createSimpleDiff("user", new String[]{user.getName(),""}));
		}
		return redirect(bean.getRedirect());
	}

	public String doEdit()
	{
		ProjectEditBean bean = new ProjectEditBean();

		if (bean.getProject() == null)
			return this.message_box(
					langRes.get("global.operation-fail"),
					langRes.get("project.project-not-exist", new String[]{bean.getRedirect()}),
					bean.getRedirect(),
					2);

		if (bean.isSubmitted() && bean.validate())
		{
			if(bean.getProject().getId() == 0)
			{
				bean.getProject().setCreatorId(getSession().getSession_uuid());
				bean.getProject().setUpdaterId(getSession().getSession_uuid());
				ProjectService.add(bean.getProject());

				OperationLogService.addLog(
						OperationLogService.OBJECT_TYPE_PROJECT,
						bean.getProject().getId(),
						getSession().getSession_uuid(),
						getContext().getActionName(),
						OperationLogService.createSimpleDiff("name", new String[]{"null", bean.getProject().getName()}));

				return this.message_box(
						langRes.get("global.operation-success"), 
						langRes.get("project.project-add-success-redirect", new String[]{bean.getRedirect()}),
						bean.getRedirect(),
						2
					);
			}
			else
			{
				Map<String, List<String>> diff = bean.getProject().compare();
				bean.getProject().setUpdaterId(getSession().getSession_uuid());
				ProjectService.update(bean.getProject());

				OperationLogService.addLog(
						OperationLogService.OBJECT_TYPE_PROJECT,
						bean.getProject().getId(),
						getSession().getSession_uuid(),
						getContext().getActionName(),
						diff);

				return this.message_box(
						langRes.get("global.operation-success"), 
						langRes.get("project.project-update-success-redirect", new String[]{bean.getRedirect()}),
						bean.getRedirect(),
						2
					);
			}
		}

		this.put_page_key("bean", bean);
		this.put_page_key("post_action", baseLink());

		return INPUT;
	}

	public class ProjectEditBean extends RequestBean
	{
		private Project project;

		public Project getProject() {
			return project;
		}

		@Override
		protected void loadRequest() 
		{
			int id = getInt("id");
			if (id > 0)
			{
				project = ProjectService.getProject(id);
			}
			else
			{
				project = new Project();
				project.initialize();
			}

			if (project != null)
			{
				if (isSubmitted())
				{
					project.setName(get("project_name"));
					project.setDescription(get("description"));
				}
			}
		}

		@Override
		protected boolean validate() 
		{
			boolean flag = true;
			if (project.getName().length() == 0)
			{
				flag = false;
				put_error_msg("project_name", langRes.get("global.content-cannot-be-empty"));
			}

			if (project.getDescription().length() == 0)
			{
				flag = false;
				put_error_msg("description", langRes.get("global.content-cannot-be-empty"));
			}

			return flag;
		}
	}
}
